package com.mongodb.service;

import com.mongodb.entity.User;
import com.mongodb.util.SnowflakeIdUtil;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

import static com.mongodb.util.CustomSnowflakeIdUtil.nextId;

@Service
public class UserService {

    @Resource
    MongoTemplate mongoTemplate;

    public void insert() {
        User user = new User();
        user.setId("mongodb" + nextId());  //该工具类需要自行生成，可百度
        user.setUsername("zhs");
        user.setPassword("123456");
        user.setCreatedTime(new Date());
        user.setUpdatedTime(new Date());
        mongoTemplate.insert(user);
    }

    public User findById(String id) {
        return mongoTemplate.findById(id, User.class);
    }

    public void update(User user) {
        user.setUpdatedTime(new Date());
        mongoTemplate.save(user);
    }

    public void delete(Long id) {
        mongoTemplate.remove(new org.springframework.data.mongodb.core.query.Query(org.springframework.data.mongodb.core.query.Criteria.where("id").is(id)), User.class);
    }

    public List<User> find() {
        Query query = new Query();
//        query.addCriteria(Criteria.where("username").is("zhsqaq"));
//        query.addCriteria(Criteria.where("password").is("zhsqaq123456"));
        query.skip(0).limit(100);
        return mongoTemplate.find(query, User.class);
    }
}
